package com.wg.msshopcar.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wg.msshopcar.entity.ShopCar;
import com.wg.msshopcar.entity.dto.*;
import com.wg.msshopcar.mapper.ShopCarMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ShopCarService extends ServiceImpl<ShopCarMapper, ShopCar> {


    // 使用DTO添加购物车
    public int addShopCar(AddShopCarDTO addShopCarDTO) {
        ShopCar shopCar = new ShopCar();
        shopCar.setUserId(addShopCarDTO.getUserId());
        shopCar.setProductId(addShopCarDTO.getProductId());
        shopCar.setSku(addShopCarDTO.getSku());
        shopCar.setCount(addShopCarDTO.getCount());
        shopCar.setPrice(addShopCarDTO.getPrice());
        shopCar.setShopId(addShopCarDTO.getShopId());
        
        // 设置添加时间
        if (addShopCarDTO.getTime() != null && !addShopCarDTO.getTime().isEmpty()) {
            shopCar.setTime(addShopCarDTO.getTime());
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            shopCar.setTime(sdf.format(new Date()));
        }
        
        return baseMapper.insert(shopCar);
    }

    // 删
    public boolean deleteShopCar(Integer id){
        return baseMapper.deleteById(id) > 0;
    }

    // 改
    public boolean updateShopCar(ShopCar shopCar){
        return baseMapper.updateById(shopCar) > 0;
    }

    // 获取所有购物车记录
    public List<ShopCar> getAllShopCars() {
        return baseMapper.selectList(null);
    }

    // 查（根据用户ID获取购物车列表
    public List<ShopCar> getShopCarsByUserId(Integer userId) {
        QueryWrapper<ShopCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return baseMapper.selectList(queryWrapper);
    }
    // ================================
    // 获取用户购物车详情（带商品、店铺、规格信息）
    public List<ShopCarDTO> getCartDetailsByUserId(Integer userId) {
        return baseMapper.selectCartDetailsByUserId(userId);
    }

    // 批量删除购物车项
    public boolean batchDeleteCartItems(List<Integer> cartIds) {
        return baseMapper.deleteBatchIds(cartIds) > 0;
    }


    // 结算
    @Transactional
    public CheckoutPackageDTO checkoutCartItems(List<Integer> cartIds) {
        // 1. 查询结算数据
        List<ShopCarDTO> checkoutData = baseMapper.selectCheckoutDataByCartIds(cartIds);
        if (checkoutData.isEmpty()) {
            throw new RuntimeException("选中的购物车项不存在");
        }

        // 2. 验证数据
        for (ShopCarDTO dto : checkoutData) {
            // 验证购买数量
            if (dto.getCount() <= 0) {
                throw new RuntimeException("商品" + dto.getProductName() + "购买数量无效");
            }
            // 验证单价
            if (dto.getPrice() == null || dto.getPrice() <= 0) {
                throw new RuntimeException("商品" + dto.getProductName() + "价格无效");
            }
        }

        // 3. 验证用户一致性
        Integer userId = checkoutData.get(0).getUserId();
        if (userId == null || userId <= 0) {
            throw new RuntimeException("用户信息无效");
        }
        boolean allSameUser = checkoutData.stream()
                .allMatch(dto -> userId.equals(dto.getUserId()));
        if (!allSameUser) {
            throw new RuntimeException("存在不属于当前用户的购物车项");
        }

        // 4. 按店铺分组
        Map<Integer, List<ShopCarDTO>> shopGroup = checkoutData.stream()
                .collect(Collectors.groupingBy(ShopCarDTO::getShopId));

        // 5. 封装订单数据（包含店铺ID、商品详情列表）
        List<ShopOrderDTO> shopOrders = new ArrayList<>();

        for (Map.Entry<Integer, List<ShopCarDTO>> entry : shopGroup.entrySet()) {
            Integer shopId = entry.getKey();
            List<ShopCarDTO> shopItems = entry.getValue();

            // 验证店铺信息
            if (shopId == null) {
                throw new RuntimeException("商品" + shopItems.get(0).getProductName() + "未关联店铺");
            }

            // 封装商品详情列表
            List<OrderDetailDTO> orderDetails = shopItems.stream()
                    .map(item -> {
                        OrderDetailDTO detail = new OrderDetailDTO();
                        detail.setProductId(item.getProductId());
                        detail.setProductName(item.getProductName());
                        detail.setProductImage(item.getProductImage());
                        detail.setCount(item.getCount());
                        detail.setPrice(item.getPrice());
                        detail.setSku(item.getSku());
                        return detail;
                    })
                    .collect(Collectors.toList());

            // 封装店铺订单
            ShopOrderDTO shopOrder = new ShopOrderDTO();
            shopOrder.setShopId(shopId);
            // 启用并设置details字段，同时可以注释掉productIds字段
            shopOrder.setDetails(orderDetails);

            // 计算店铺总金额（如果需要）
            // double shopTotal = orderDetails.stream()
            //         .mapToDouble(detail -> detail.getPrice() * detail.getCount())
            //         .sum();
            // shopOrder.setTotalAmount(shopTotal);
            // shopOrder.setShopName(shopItems.get(0).getShopName()); // 假设能获取店铺名称

            shopOrders.add(shopOrder);
        }

        // 6. 封装结算数据包
        CheckoutPackageDTO checkoutPackage = new CheckoutPackageDTO();
        checkoutPackage.setUserId(userId);
        checkoutPackage.setShopOrders(shopOrders);
        checkoutPackage.setCartIds(cartIds);

        // 计算总支付金额（如果需要）
        // double totalPayment = shopOrders.stream()
        //         .filter(shopOrder -> shopOrder.getTotalAmount() != null)
        //         .mapToDouble(ShopOrderDTO::getTotalAmount)
        //         .sum();
        // checkoutPackage.setTotalPayment(totalPayment);

        return checkoutPackage;
    }


    // 结算购物车商品
   /* @Transactional
    public CheckoutPackageDTO checkoutCartItems(List<Integer> cartIds) {
        // 1. 查询结算数据
        List<ShopCarDTO> checkoutData = baseMapper.selectCheckoutDataByCartIds(cartIds);
        if (checkoutData.isEmpty()) {
            throw new RuntimeException("选中的购物车项不存在");
        }

        // 2. 验证数据
        for (ShopCarDTO dto : checkoutData) {
            // 验证购买数量
            if (dto.getCount() <= 0) {
                throw new RuntimeException("商品" + dto.getProductName() + "购买数量无效");
            }
            // 验证单价
            if (dto.getPrice() == null || dto.getPrice() <= 0) {
                throw new RuntimeException("商品" + dto.getProductName() + "价格无效");
            }
        }

        // 3. 验证用户一致性
        Integer userId = checkoutData.get(0).getUserId();
        if (userId == null || userId <= 0) {
            throw new RuntimeException("用户信息无效");
        }
        boolean allSameUser = checkoutData.stream()
                .allMatch(dto -> userId.equals(dto.getUserId()));
        if (!allSameUser) {
            throw new RuntimeException("存在不属于当前用户的购物车项");
        }

        // 4. 按店铺分组
        Map<Integer, List<ShopCarDTO>> shopGroup = checkoutData.stream()
                .collect(Collectors.groupingBy(ShopCarDTO::getShopId));

        // 5. 封装订单数据
        List<ShopOrderDTO> shopOrders = new ArrayList<>();

        for (Map.Entry<Integer, List<ShopCarDTO>> entry : shopGroup.entrySet()) {
            Integer shopId = entry.getKey();
            List<ShopCarDTO> shopItems = entry.getValue();

            // 验证店铺信息
            if (shopId == null) {
                throw new RuntimeException("商品" + shopItems.get(0).getProductName() + "未关联店铺");
            }

            // 只封装商品ID列表
            List<Integer> productIds = shopItems.stream()
                    .map(ShopCarDTO::getProductId)
                    .collect(Collectors.toList());

            // 封装店铺订单（只保留店铺ID和商品ID列表）
            ShopOrderDTO shopOrder = new ShopOrderDTO();
            shopOrder.setShopId(shopId);
            shopOrder.setProductIds(productIds);

            shopOrders.add(shopOrder);


        }

        // 6. 封装结算数据包
        CheckoutPackageDTO checkoutPackage = new CheckoutPackageDTO();
        checkoutPackage.setUserId(userId);
        checkoutPackage.setShopOrders(shopOrders);
        checkoutPackage.setCartIds(cartIds);

        return checkoutPackage;
    }
*/

    /*// 结算购物车商品
    @Transactional
    public CheckoutPackageDTO checkoutCartItems(List<Integer> cartIds) {
        // 1. 查询结算数据
        List<ShopCarDTO> checkoutData = baseMapper.selectCheckoutDataByCartIds(cartIds);
        if (checkoutData.isEmpty()) {
            throw new RuntimeException("选中的购物车项不存在");
        }

        // 2. 验证数据
        for (ShopCarDTO dto : checkoutData) {
            // 验证购买数量
            if (dto.getCount() <= 0) {
                throw new RuntimeException("商品" + dto.getProductName() + "购买数量无效");
            }
            // 验证单价
            if (dto.getPrice() == null || dto.getPrice() <= 0) {
                throw new RuntimeException("商品" + dto.getProductName() + "价格无效");
            }

        }

        // 3. 验证用户一致性
        Integer userId = checkoutData.get(0).getUserId();
        if (userId == null || userId <= 0) {
            throw new RuntimeException("用户信息无效");
        }
        boolean allSameUser = checkoutData.stream()
                .allMatch(dto -> userId.equals(dto.getUserId()));
        if (!allSameUser) {
            throw new RuntimeException("存在不属于当前用户的购物车项");
        }

        // 4. 按店铺分组
        Map<Integer, List<ShopCarDTO>> shopGroup = checkoutData.stream()
                .collect(Collectors.groupingBy(ShopCarDTO::getShopId));

        // 5. 封装订单数据
        List<ShopOrderDTO> shopOrders = new ArrayList<>();
        double totalPayment = 0.0;

        for (Map.Entry<Integer, List<ShopCarDTO>> entry : shopGroup.entrySet()) {
            Integer shopId = entry.getKey();
            List<ShopCarDTO> shopItems = entry.getValue();

            // 验证店铺信息
            if (shopId == null || shopItems.get(0).getShopName() == null) {
                throw new RuntimeException("商品" + shopItems.get(0).getProductName() + "店铺信息不完整");
            }

            // 计算店铺总金额
            double shopTotal = shopItems.stream()
                    .mapToDouble(dto -> dto.getPrice() * dto.getCount())
                    .sum();
            totalPayment += shopTotal;

            // 封装订单详情
            List<OrderDetailDTO> details = shopItems.stream().map(dto -> {
                OrderDetailDTO detail = new OrderDetailDTO();
                detail.setProductId(dto.getProductId());
                detail.setProductName(dto.getProductName());
                detail.setProductImage(dto.getProductImage());
                detail.setCount(dto.getCount());
                detail.setPrice(dto.getPrice());
                detail.setSku(dto.getSku());
                return detail;
            }).collect(Collectors.toList());

            // 封装店铺订单
            ShopOrderDTO shopOrder = new ShopOrderDTO();
            shopOrder.setShopId(shopId);
            shopOrder.setShopName(shopItems.get(0).getShopName());
            shopOrder.setTotalAmount(shopTotal);
            shopOrder.setDetails(details);

            shopOrders.add(shopOrder);
        }

        // 6. 封装结算数据包
        CheckoutPackageDTO checkoutPackage = new CheckoutPackageDTO();
        checkoutPackage.setUserId(userId);
        checkoutPackage.setShopOrders(shopOrders);
        checkoutPackage.setTotalPayment(totalPayment);
        checkoutPackage.setCartIds(cartIds);

        return checkoutPackage;
    }*/
}